<?php

namespace app\admin\controller\paotui;


use addons\paotui\service\Config;
use app\admin\model\paotui\PosterMoneyLog;
use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 用户提现管理
 *
 * @icon fa fa-circle-o
 */
class Posterextract extends Backend
{
    
    /**
     * Posterextract模型对象
     * @var \app\admin\model\paotui\Posterextract
     */
    protected $model = null;
    protected $relationSearch = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\paotui\Posterextract;

    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->alias("posterextract")
                ->field("posterextract.*,poster.poster_name")
                ->join("paotui_poster poster","posterextract.poster_id=poster.id")
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }




    /**
     * 确认提现
     */
    public function succ($ids){

        $userExtractModel = new \app\admin\model\paotui\PosterExtract();
        $userExtract = $userExtractModel->where(['status'=>0,'id'=>$ids])->find();
        if(!$userExtract){
            $this->error('请求参数不存在');
        }

        $posterModel = new \app\admin\model\paotui\Poster();
        $posterInfo = $posterModel->where(['id'=>$userExtract['poster_id']])->find();
        if(!$posterInfo){
            $this->error('当前骑手不存在');
        }

        //获取佣金结算类型
        $pay_type = Config::get('pay_type');

        if($pay_type == 1){
            Db::startTrans();
            if($userExtract->save(['status'=>1,'checktime'=>time()])){
                $after = bcsub($posterInfo['money'],$userExtract['extract_price'],2);
                $posterMoneyLogModel = new PosterMoneyLog();
                if(!$posterMoneyLogModel->save([
                    'poster_id'=>$posterInfo['id'],
                    'type'=>'extract',
                    'source_id'=>$userExtract['id'],
                    'money'=>-$userExtract['extract_price'],
                    'before'=>$posterInfo['money'],
                    'after'=>$after,
                    'memo'=>'佣金提现'
                ])){
                    Db::rollback();
                    $this->error("提现失败，请联系管理员");
                }

                if(!$posterInfo->save(['money'=>$after])){
                    Db::rollback();
                    $this->error("提现失败，请联系管理员");
                }

                Db::commit();
                $this->success('请求成功');
            }else{
                Db::rollback();
                $this->error('请求失败');
            }
        }

        $this->error('请求失败');


    }

    public function cancel($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $params['status'] = -1;
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

}
